//
//  HWRemindLabel.m
//  OCDome
//
//  Created by 李含文 on 2021/2/6.
//  Copyright © 2021 李含文. All rights reserved.
//

#import "HWRemindLabel.h"
#import <objc/runtime.h>

@interface HWRemindLabel()

/// 自适应后的尺寸
@property (nonatomic, assign) CGSize badgeSize;

@end

@implementation HWRemindLabel

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)setUI {
    _minSize = HWRemindLabel_minSize();
    _spacing = HWRemindLabel_spacing();
    _badgeSize = _minSize;
    _maxNum = HWRemindLabel_maxNum();
    self.hidden = YES;
}

- (void)setSpacing:(CGFloat)spacing {
    _spacing = spacing;
    [self resetUI];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    [super setBackgroundColor:backgroundColor];
    [self resetUI];
}

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    [self resetUI];
}

- (void)setText:(NSString *)text {
    NSString *tmp = text;
    if (tmp.intValue > self.maxNum) {
        tmp = [NSString stringWithFormat:@"%ld+", self.maxNum];
    }
    [super setText:tmp];
    [self resetUI];
}

- (void)setMinSize:(CGSize)minSize {
    _minSize = minSize;
    _badgeSize = minSize;
    [self resetUI];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.badgeSize.width, self.badgeSize.height);
    if (self.layer.cornerRadius == self.bounds.size.height*0.5) {return;}
    self.layer.cornerRadius = self.bounds.size.height*0.5;
    self.layer.masksToBounds = YES;
}

- (void)resetUI {
    if (self.text.length == 0) return;
    if (!self.backgroundColor) { // 因为其他都有默认值就它没有 就用它了吧
        self.backgroundColor = HWRemindLabel_backgroundColor();
        self.font = [UIFont systemFontOfSize:HWRemindLabel_font()];
        self.textColor = HWRemindLabel_textColor();
        self.textAlignment = NSTextAlignmentCenter;
        [self resetUI];
        return;
    }
    if (self.text.intValue <= 0) {
        self.hidden = YES;
    } else {
        self.hidden = NO;
        CGSize badgeSize = CGSizeMake(self.minSize.height, self.minSize.width);
        [self sizeToFit];
        CGFloat w = self.bounds.size.width;
        if (w+self.spacing < badgeSize.width) {
            badgeSize = CGSizeMake(self.bounds.size.height, badgeSize.height);
        } else {
            badgeSize = CGSizeMake(w+self.spacing, badgeSize.height);
        }
        _badgeSize = badgeSize;
        self.bounds = CGRectMake(0, 0, badgeSize.width, badgeSize.height);
    }
}

@end
